( function ( D )
{
    D.request = function ( sparqlFile, patterns, doer, post, blocking )
    {
        var hrq1 = new XMLHttpRequest( );
        var request1 = "http://desanti.org/requests/" + sparqlFile;

        hrq1.open( "GET", request1, false );
        hrq1.send( null );

        var sparqlRequest = hrq1.responseText;

        for( var pattern in patterns )
        {
            var reg = new RegExp( '\\|' + pattern + '\\|', "g" );
            sparqlRequest = sparqlRequest.replace( reg, patterns[ pattern ] ); 
        }

        var hrq2 = new XMLHttpRequest( );

        var onload = function( )
        {
            if( doer )
            {
                var data  = eval( "(" + hrq2.responseText + ")" );
                if( data.results )
                {
                    doer( data.results.bindings );
                }
                else
                {
                    doer( data );
                }
            }
        }

        hrq2.onload = onload; 

        if( post )
        {
	        //console.log(sparqlRequest);
	        //if(doer) doer();
            var request2 = "query=" + encodeURIComponent( sparqlRequest );

            hrq2.open( "POST", "http://desanti.org/endpoint.php?output=json" );
            hrq2.send( request2 );
        }
        else
        {
            var request2 = "http://desanti.org/endpoint.php?output=json&query=" + 
                           encodeURIComponent( sparqlRequest );

            if( blocking )
            {
                hrq2.open( "GET", request2, false );
                hrq2.send( null );
                onload( );
            }
            else
            {
                hrq2.open( "GET", request2, true );
                hrq2.send( null );
            }
        }
    }

} ) ( DESANTI );
